/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.app;

import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import of.hotswapinject.agent.AgentAttach;
import of.hotswapinject.agent.JarFileHelper;
import of.hotswapinject.agent.PluginInstallContext;
import of.hotswapinject.core.common.Const;
import of.hotswapinject.core.common.Util;
import org.apache.commons.cli.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Command {
    private static String pid = null;

    public static CommandLine getCommandLine(PluginInstallContext context, String[] args) {
        Options options = context.options;
        CommandLineParser parser = new DefaultParser();
        try{
            CommandLine cmd = parser.parse(options, args);
            if(cmd.hasOption("pid")) {
                pid = cmd.getOptionValue("pid");
            }
            if(pid == null || "".equals(pid)) {
                System.out.println("pid can't be empty!");
                new HelpFormatter().printHelp("utility-name", options);
            }
            else if(args == null || args.length == 0 || (args.length == 1 && "".equals(args[0]))) {
                new HelpFormatter().printHelp("utility-name", options);
            }
            return cmd;
        } catch (ParseException e) {
            Util.trace(e.getMessage());
            new HelpFormatter().printHelp("utility-name", options);
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String jarPath = JarFileHelper.getLocalJarPath();
        PluginInstallContext context = new PluginInstallContext();
        System.out.println("jarPath:" + jarPath);//undo:out.println should check
        context.init(jarPath);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                System.in));
        while(true) {
            try {
                CommandLine cmd = getCommandLine(context, args);
                if(cmd != null) {
                    if(cmd.hasOption("javaProcess")) {
                        System.out.println("list java process:");
                        for(VirtualMachineDescriptor vmd : VirtualMachine.list()) {
                            System.out.println("name:" + vmd.displayName() + ",id:" + vmd.id());
                        }
                    }

                    try {
                        if(pid != null && !("".equals(pid))) {
                            AgentAttach.attach(pid, args);
                        }

                    } catch (Exception e) {
                        pid = null;
                        e.printStackTrace();
                    }
                }
                System.out.println(Const.NEWLINE);
                System.out.println("last command is:" + String.join(" ", args));
                System.out.println("please insert command again:");
                String line = br.readLine();
                args = line.split(" ");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}